// src/components/SysHeader.vue
<template>
    <div class="header-box">
        <div class="title">
            <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
            >
                <el-avatar 
                    :size="40" 
                    :src="avatarUrl || defaultAvatar"
                    @error="handleAvatarError"
                />
            </el-upload>
            <span style="margin-left: 10px;">考试系统</span>
        </div>
        <el-dropdown>
            <span class="el-dropdown-link">
                <!-- 显示用户名 -->
                {{ userInfo.type === 'teacher' ? '老师' : (userInfo.studentId || '未登录') }}<el-icon class="el-icon-right"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item :icon="EditPen" @click="goToEditPassword">修改密码</el-dropdown-item>
                    <el-dropdown-item :icon="SwitchButton" @click="logout">安全退出</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </div>
</template>

<script setup>
import { ArrowDown, EditPen, SwitchButton } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue';
import { useUser } from '@/stores/userInfo';
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

// 引入用户信息存储
const userStore = useUser()
// 使用 storeToRefs 解构用户信息，确保响应式
const { userInfo } = storeToRefs(userStore)
const router = useRouter();

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
// 当前头像URL
const avatarUrl = ref('')

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG) {
        ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    }
    if (!isLt2M) {
        ElMessage.error('头像大小不能超过 2MB!')
    }
    return isJPG && isLt2M
}

// 处理头像上传
const handleAvatarUpload = async (options) => {
    try {
        const file = options.file
        // 将文件转换为 base64
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
            avatarUrl.value = reader.result
            // 保存到 sessionStorage
            sessionStorage.setItem('userAvatar', reader.result)
            // 更新用户信息中的头像
            if (userInfo.value) {
                userInfo.value.avatar = reader.result
                sessionStorage.setItem('userInfo', JSON.stringify(userInfo.value))
            }
            ElMessage.success('头像更新成功')
        }
    } catch (error) {
        console.error('头像上传失败:', error)
        ElMessage.error('头像上传失败')
    }
}

// 处理头像加载错误
const handleAvatarError = () => {
    avatarUrl.value = defaultAvatar
}

// 跳转到修改密码页面
const goToEditPassword = () => {
    router.push('/main/self/pwd');
};

// 安全退出
const logout = () => {
    // 保存当前头像
    const currentAvatar = sessionStorage.getItem('userAvatar')
    // 清空用户信息
    userStore.SET_USER_INFO({});
    // 清空 sessionStorage
    sessionStorage.clear();
    // 恢复头像
    if (currentAvatar) {
        sessionStorage.setItem('userAvatar', currentAvatar)
    }
    // 跳转到登录页面
    router.push('/login');
};

// 在组件挂载时检查用户信息
onMounted(() => {
    console.log('用户信息:', userInfo.value); 
    // 如果用户信息为空，可能需要重新从 sessionStorage 加载
    if (!userInfo.value || !userInfo.value.studentId) {
        const storedUserInfo = sessionStorage.getItem('userInfo');
        if (storedUserInfo) {
            userStore.SET_USER_INFO(JSON.parse(storedUserInfo));
        }
    }
    // 加载保存的头像
    const savedAvatar = sessionStorage.getItem('userAvatar')
    if (savedAvatar) {
        avatarUrl.value = savedAvatar
        // 如果用户信息中没有头像，则更新用户信息
        if (userInfo.value && !userInfo.value.avatar) {
            userInfo.value.avatar = savedAvatar
            sessionStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        }
    }
});
</script>

<style scoped>
.header-box {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    background-color: #409EFF;
    color: white;
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.title {
    display: flex;
    align-items: center;
}

.avatar-uploader {
    cursor: pointer;
}

.avatar-uploader :deep(.el-upload) {
    border-radius: 50%;
    overflow: hidden;
}

.el-dropdown-link{
    margin-right: 60px;
    color: white;
}

.el-dropdown {
    color: white;
}
</style>